<!-- 试卷操作(添加、编辑) -->
<template>
  <div class="form-container">
    <div class="paper-form">
      <el-form ref="paperForm" :model="paperForm" :inline="true" :rules="rules" label-position="right" label-width="100px" hide-required-asterisk @submit.native.prevent>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('paperLangList.paperName')" prop="title">
              <el-input :placeholder="$t('paperLangList.inputPaperName')" v-model="paperForm.title" maxlength="50" show-word-limit/>
              <label><span style="color: red">*</span>(必填)支持中文、字母、数字、英文单引号和'_'以及'-'，长度不要超过50个字符</label>
            </el-form-item>
            <el-form-item :label="$t('paperLangList.uploadCover')">
              <img :src="paperCoverImage" class="upload-image">
              <el-upload ref="coverUpload" :show-file-list="false" :accept="acceptFileExt" :http-request="uploadCover" :on-change="uploadCoverChange" :auto-upload="false" :limit="1" class="upload-btn" action="">
                <el-button v-if="paperForm.imgUrl === ''" slot="trigger" size="small" type="primary">{{ $t('paperLangList.uploadCoverBtn') }}</el-button>
                <template v-else>
                  <el-button slot="trigger" size="small" type="primary" @click="reUploadCover">{{ $t('paperLangList.reUploadCoverBtn') }}</el-button>
                  <el-button size="small" type="primary" style="margin-left: 96px" @click="deleteUploadCover">{{ $t('paperLangList.delUploadCoverBtn') }}</el-button>
                </template>
                <div slot="tip"><label>*(非必填)点击上面按钮上传图片。建议：JPG或者PNG图片，推荐480*640></label></div>
              </el-upload>
            </el-form-item>
            <el-form-item :label="$t('paperLangList.remark')" prop="note">
              <el-input :rows="6" v-model="paperForm.note" type="textarea" maxlength="1000" show-word-limit/>
              <label>(非必填)可填英文、数字或汉字，长度不要超1000个字符</label>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="form-footer">
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="savePaper(1)">{{ $t('form.saveAsExit') }}</el-button>
        <el-button type="primary" @click="savePaper(2)">{{ $t('paperLangList.save') }}</el-button>
      </el-row>
    </div>
  </div>
</template>

<script>
import paperCoverPng from '@/assets/paper_images/paper-cover.png'
import { createPaper, updatePaper, uploadPaperCover } from '@/api/paper'
export default {
  name: 'PaperOperate',
  data() {
    return {
      paperForm: {
        title: '',
        imgUrl: '',
        note: ''
      },
      rules: {
        title: [
          { required: true, message: this.$t('paperLangList.paperName') + this.$t('form.notNull'), trigger: 'change' },
          { min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur' }
        ]
      },
      acceptFileExt: '.jpeg,.jpg,.gif,.png',
      fileObj: null,
      paperId: '',
      btnType: 1
    }
  },
  computed: {
    'paperCoverImage': function() {
      let imageUrl = this.paperForm.imgUrl || paperCoverPng
      if (this.fileObj && this.fileObj !== null) {
        imageUrl = URL.createObjectURL(this.fileObj.raw)
      }
      return imageUrl
    }
  },
  methods: {
    // 初始化
    initForm() {
      this.paperForm = {
        title: '',
        imgUrl: '',
        note: ''
      }
      this.paperId = ''
      this.fileObj = null
      this.$refs.coverUpload.clearFiles()
      this.$nextTick(() => {
        this.$refs['paperForm'].clearValidate()
      })
    },
    // 初始化更新数据
    initPaperDetail(row) {
      this.paperForm.title = row.title
      this.paperForm.imgUrl = row.imgUrl
      this.paperForm.note = row.note
      this.paperId = row.id
    },
    // 上传试卷封面回调
    uploadCoverChange(file, fileList) {
      console.info(fileList)
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      if (this.acceptFileExt.indexOf(fileExt) === -1) {
        this.$message({
          message: '不允许上传' + fileExt + '文件',
          type: 'error'
        })
      } else {
        this.fileObj = file
      }
      console.info(file)
    },
    // 重新上传
    reUploadCover() {
      this.$refs.coverUpload.clearFiles()
    },
    // 删除图片
    deleteUploadCover() {
      this.$refs.coverUpload.clearFiles()
      this.fileObj = null
      this.paperForm.imgUrl = ''
    },
    // 试卷操作
    savePaper(btnType) {
      const _this = this
      _this.btnType = btnType
      _this.$refs['paperForm'].validate((valid) => {
        if (valid) {
          const loading = _this.$loading({
            lock: true,
            text: '数据保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.6)'
          })
          // 添加操作
          if (_this.paperId === '') {
            createPaper(_this.paperForm).then(res => {
              if (res) {
                // 需要上传文件
                if (_this.fileObj) {
                  _this.paperId = res.id
                  _this.$refs.coverUpload.submit()
                } else {
                  _this.$emit('callbackEmit', this.btnType, _this.paperId)
                }
                loading.close()
              }
            })
          }
          // 更新操作
          else {
            updatePaper(_this.paperId, _this.paperForm).then(res => {
              if (res) {
                // 需要上传文件
                if (_this.fileObj) {
                  _this.$refs.coverUpload.submit()
                } else {
                  _this.$emit('callbackEmit', this.btnType, _this.paperId)
                }
                loading.close()
              }
            })
          }
        }
      })
    },
    // 上传试卷封面
    async uploadCover() {
      const data = new FormData()
      data.append('paperId', this.paperId)
      data.append('image', this.fileObj.raw)
      await uploadPaperCover(data)
      this.$emit('callbackEmit', this.btnType, this.paperId)
    }
  }
}
</script>

<style lang="less" scoped>
  .form-container {
    height: 640px;
    position: relative;
    .paper-form {
      height: 600px;
      overflow-y: auto;
    }
    .form-footer {
      position: absolute;
      bottom: 0;
      width: 100%;
    }
  }
  .upload-image {
    width: 260px;
    height: 300px;
  }
</style>
